package file

import (
	"context"
	"git.mycaigou.com/gfyx/common/tenant_db"
	"gorm.io/gorm"
)

type fileRepository struct {
	tenant_db.TenantDB
}

func NewFileRepository() FileRepoIface {
	return &fileRepository{}
}

func (r *fileRepository) SaveFile(ctx context.Context, po *GfyxFilesPo) (*GfyxFilesPo, error) {
	db := r.GetTenantDB(ctx)
	err := db.Save(po).Error
	if err != nil {
		return nil, err
	}
	return po, nil
}

func (r *fileRepository) QueryById(ctx context.Context, fileId int64) (*GfyxFilesPo, error) {
	var result GfyxFilesPo
	err := r.GetTenantDB(ctx).Table(result.TableName()).Where("id = ? and is_deleted = 0", fileId).First(&result).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, nil
		}
		return nil, err
	}
	return &result, nil
}

func (r *fileRepository) QueryByIds(ctx context.Context, fileIds []int64) ([]*GfyxFilesPo, error) {
	var list []*GfyxFilesPo
	err := r.GetTenantDB(ctx).Table(GfyxFilesPo{}.TableName()).Where("id in (?) and is_deleted = 0", fileIds).Find(&list).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, nil
		}
		return nil, err
	}
	return list, nil
}
